package edu.seu.mart.web;

import edu.seu.mart.model.Admin;
import edu.seu.mart.model.Seller;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SellerLoginFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hsq = (HttpServletRequest)req;
        String uri=hsq.getRequestURI();
        HttpSession session = hsq.getSession();
		/*
		 * 如果使用uploadify进行文件的上传，由于flash的bug问题，会产生一个新的session，此时验证失败
		 * 所以必须在此处获取一个原有的session，然后重置session信息
		 */
        String sid = hsq.getParameter("sid");
        if(sid!=null&&!"".equals(sid.trim())) {
            //当sid有值，就表示是通过uploadify上传文件，此时就应该获取原有的session
            session = SessionContext.getSession(sid);
        }
        if(uri.indexOf("seller/login")==-1){
            Seller u = (Seller)session.getAttribute("seller");
            if(u==null) {
                ((HttpServletResponse)resp).sendRedirect(hsq.getContextPath()+"/seller/login");
            }else{
                chain.doFilter(req, resp);
            }
        }else{
            chain.doFilter(req, resp);
        }
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
